package com.vitabuybuy.tv.ui.mine.order.after

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.GridLayoutManager
import com.luck.picture.lib.PictureSelector
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.dialog.RefundResonDialog
import com.vitabuybuy.tv.dto.OrderDetailDto
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.dto.MessageEvent
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.toast.XToast
import com.library.common.util.PictureUtils
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.databinding.ActivityRequestRefundBinding
import com.vitabuybuy.tv.ui.mine.order.adapter.PictureAdapter
import com.vitabuybuy.tv.ui.mine.order.after.viewmodel.AfterSaleViewModel
import com.vitabuybuy.tv.utils.EventCode
import com.vitabuybuy.tv.utils.StringUtil
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_request_refund.*
import org.greenrobot.eventbus.EventBus

class RequestRefundActivity : BaseActivity<AfterSaleViewModel, ActivityRequestRefundBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_request_refund

    private var itemBean: OrderDetailDto.ItemListBean? = null
    private var returnType = 0
    private var refundId = -1
    private var REQUEST_CODE_CAMMER = 0x11
    private val picAdapter by lazy { PictureAdapter(3) }
    override fun onGetBundle(bundle: Bundle?) {
        itemBean = bundle?.getSerializable("itemBean") as OrderDetailDto.ItemListBean
        refundId = bundle.getInt("refundId")
        returnType = bundle.getInt("returnType")
    }

    override fun initView(savedInstanceState: Bundle?) {
        when (returnType) {
            AFTER_SALE_TYPE_BY_ONLY_RETUAN_MONEY -> setTitle(getString(R.string.request_return_only_money))
            AFTER_SALE_TYPE_BY_RETURN_GOODS_AND_RETUAN_MONEY -> setTitle(getString(R.string.request_return_goods_money))
        }
        itemBean?.run {
            tvCommodityTitle.text = this.product.name
            tvPrice.text = String.format(getString(R.string.price_with_value), this.price)
            tvCount.text = String.format(getString(R.string.x), this.quantity)
            tvQuantity.text = this.quantity.toString()
            tvType.text = this.specifications
            tvAmount.text =
                String.format(getString(R.string.price_with_value), this.price * this.quantity)
            ImageAdapter.setNomalImageUrl(
                ivImage, this.goods.image,
                ContextCompat.getDrawable(mContext, R.drawable.default_image)
            )
        }
        recyclerView.apply {
            adapter = picAdapter
            layoutManager = GridLayoutManager(mContext, 4)
            isNestedScrollingEnabled = false
        }
    }

    override fun eventHandling() {
        setOnclickNoRepeat(rlReason, btnSubmitApplication, ivMinus, ivAdd){v->
            when (v) {
                ivMinus -> {
                    var quantity = tvQuantity.text.toString().toInt()
                    if (quantity == 1) {
                        return@setOnclickNoRepeat
                    }
                    quantity = quantity - 1
                    tvQuantity.text = (quantity).toString()
                    itemBean?.price?.run {
                        mBinding.tvAmount.text =
                            String.format(
                                getString(R.string.price_with_value),
                                this * quantity
                            )
                    }
                }
                ivAdd -> {
                    var quantity = tvQuantity.text.toString().toInt()
                    if (quantity == itemBean?.quantity) {
                        return@setOnclickNoRepeat
                    }
                    quantity = quantity + 1
                    tvQuantity.text = (quantity).toString()
                    itemBean?.price?.run {
                        mBinding.tvAmount.text =
                            String.format(
                                getString(R.string.price_with_value),
                                this * quantity
                            )
                    }
                }
                rlReason -> {
                    RefundResonDialog(mContext, returnType) {
                        tvReson.text = it
                    }.showPopupWindow()
                }
                btnSubmitApplication -> {
                    when {
                        tvReson.text.isNullOrEmpty() -> XToast.normal(getString(R.string.click_to_choose_reason))
                        etReson.text.isNullOrEmpty() -> XToast.normal(getString(R.string.explanation_tip))
                        else -> {
                            val params = HashMap<String, Any>()
                            if (refundId != -1) {
                                params["id"] = refundId
                                params["reason"] = tvReson.text.toString()
                                params["buyerDescription"] = etReson.text.toString()
                                if (!picAdapter.mData.isNullOrEmpty()) {
                                    var images = ""
                                    for (image in picAdapter.mData) {
                                        images = "$images$image,"
                                    }
                                    params["images"] = StringUtil.replaceEndChar(images)
                                }
                                viewModel.modifyAfterSale(params)
                            } else {
                                params["type"] = when (returnType) {
                                    AFTER_SALE_TYPE_BY_ONLY_RETUAN_MONEY -> getString(R.string.refund_1)
                                    AFTER_SALE_TYPE_BY_RETURN_GOODS_AND_RETUAN_MONEY -> getString(R.string.return_goods_money)
                                    else -> ""
                                }
                                params["quantity"] = tvQuantity.text.toString()
                                params["reason"] = tvReson.text.toString()
                                params["buyerDescription"] = etReson.text.toString()
                                if (!picAdapter.mData.isNullOrEmpty()) {
                                    var images = ""
                                    for (image in picAdapter.mData) {
                                        images = "$images$image,"
                                    }
                                    params["images"] = StringUtil.replaceEndChar(images)
                                }
                                params["item"] = mapOf(Pair("id", itemBean?.id))
                                viewModel.applyReson(params)
                            }
                        }
                    }
                }
            }
        }
        picAdapter.setOnClickDeleteListener {
            picAdapter.removeAt(it)
        }
        picAdapter.setOnItemClickListener { _, position ->
            if (position == picAdapter.mData.size) {
                AndPermission.with(this)
                    .runtime()
                    .permission(
                        Permission.Group.CAMERA,
                        Permission.Group.STORAGE
                    )
                    .onDenied {
                        if (AndPermission.hasAlwaysDeniedPermission(this, it)) {
                            // 这些权限被用户总是拒绝。
                            XToast.normal(getString(R.string.request_necessary_permissions))
                        }
                    }
                    .onGranted {
                        PictureUtils.openAluamMore(
                            mContext,
                            REQUEST_CODE_CAMMER,
                            (3 - picAdapter.mData.size)
                        )
                    }.start()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == REQUEST_CODE_CAMMER) {
            val images = ArrayList<String>()
            for (image in PictureSelector.obtainMultipleResult(data)) {
                images.add(image.compressPath)
            }
            viewModel.uploadImage(images)
        }
    }


    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                if (picAdapter.mData.size == 0)
                    picAdapter.setNewData(msg.obj as ArrayList<String>)
                else
                    picAdapter.addData(msg.obj as ArrayList<String>)
            }
            2 -> {
                EventBus.getDefault().post(MessageEvent(EventCode.update_order_detail))
                XToast.success(getString(R.string.apply_after_sale_success))
                finishResult(null)
            }
        }
    }

    companion object {
        const val AFTER_SALE_TYPE_BY_RETURN_GOODS_AND_RETUAN_MONEY = 1001
        const val AFTER_SALE_TYPE_BY_ONLY_RETUAN_MONEY = 1002
        fun openActivity(
            mContext: BaseActivity<*, *>,
            itemBean: OrderDetailDto.ItemListBean,
            refundId: Int?,
            returnType: Int
        ) {
            mContext.startForResult(
                bundleOf(
                    Pair("itemBean", itemBean),
                    Pair("refundId", refundId),
                    Pair("returnType", returnType)
                ), 1001,
                RequestRefundActivity::class.java
            )
        }
    }
}
